using MonoMod.Utils;
using Terraria.Localization;

namespace RSCore;

public class TranslationHook : IDisposable
{
	public static TranslationHook Instance => instance ??= new TranslationHook();

	public bool Enable { get; set; } = true;

	public void AddTranslation(Dictionary<string, TextPair> translations, string modName)
	{
		foreach(var (key, pair) in translations)
		{
			_translations[$"Mods.{modName}.{key}"] = pair;
		}
	}

	public void Dispose()
	{
		_translations.Clear();
		On_LanguageManager.LoadFilesForCulture -= On_LanguageManager_LoadFilesForCulture;
		instance = null;
		GC.SuppressFinalize(this);
	}

	private static TranslationHook? instance;

	private Dictionary<string, TextPair> _translations = new();

	private TranslationHook()
	{
		On_LanguageManager.LoadFilesForCulture += On_LanguageManager_LoadFilesForCulture;
	}

	private void On_LanguageManager_LoadFilesForCulture(On_LanguageManager.orig_LoadFilesForCulture orig, LanguageManager self, GameCulture culture)
	{
		orig.Invoke(self, culture);
		if (!Enable)
		{
			return;
		}

		foreach (var (key, pair) in _translations)
		{
			if (LanguageManager.Instance._localizedTexts.TryGetValue(key, out var localizedText))
			{
				if (pair.Origin == null || pair.Origin == localizedText.Value)
				{
					localizedText.SetValue(pair.Translation);
				}
			}
		}
	}
}